package com.yeskery.nut.cloud.loadbanlancer;

import com.yeskery.nut.cloud.registry.core.Instance;
import com.yeskery.nut.cloud.registry.core.Server;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 轮询选择器
 * @author YESKERY
 * 2024/1/4
 */
public class RoundChooser extends BaseChooser {

    /** 轮询索引map */
    private static final Map<String, Integer> roundIndexMap = new ConcurrentHashMap<>(16);

    @Override
    protected Instance doChoose(Server server) {
        String serverName = server.name();
        List<Instance> instances = server.getInstances();
        int instanceSize = instances.size();
        Integer index = roundIndexMap.putIfAbsent(serverName, 0);
        if (index == null) {
            index = roundIndexMap.get(serverName);
        }
        if (index < 0){
            index = 0;
        }  else if (index >= instanceSize) {
            index = instanceSize - 1;
        }
        int newIndex = index + 1;
        if (newIndex >= instanceSize) {
            newIndex = 0;
        }
        roundIndexMap.put(serverName, newIndex);
        return instances.get(index);
    }
}
